<template>
<div>
  <bread ref="bread"></bread>
  <el-card>
    <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" :closable="false" show-icon></el-alert>
    <el-row style="margin: 15px 0">
      <el-col>
        <span>选择商品分类：</span>
        <el-cascader
            v-model="selectedKey"
            :options="cateList"
            :props="{ expandTrigger: 'hover', value:'cat_id',label:'cat_name',children:'children'}"
            @change="parentCateChange">
        </el-cascader>
      </el-col>
    </el-row>
<!--    数据表格-->
    <el-tabs v-model="activeName" @tab-click="handleTabClick">
      <el-tab-pane label="动态参数" name="many" :disabled="Button">
        <el-button type="primary" size="mini" :disabled="Button" @click="addDialog=true">添加参数</el-button>
        <el-table :data="manyTableData" border stripe>
          <el-table-column type="expand">
           <template slot-scope="scope">
             <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable
                     @close="deleteTag(index,scope.row)">
               {{ item }}
             </el-tag>
<!--             添加标签-->
             <el-input
                 class="input-new-tag"
                 v-if="scope.row.inputVisable"
                 v-model="scope.row.inputValue"
                 ref="saveTagInput"
                 size="small"
                 @keyup.enter.native="handleInputConfirm(scope.row)"
                 @blur="handleInputConfirm(scope.row)"
                 style="width:150px"
                 >
             </el-input>
             <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
           </template>
          </el-table-column>
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column label="参数名称" prop="attr_name"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)"></el-button>
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParams(scope.row.attr_id)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="静态属性" name="only" :disabled="Button">
        <el-button type="primary" size="mini" :disabled="Button" @click="addDialog=true">添加属性</el-button>
        <el-table :data="onlyTableData" border stripe>
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable
                      @close="deleteTag(index,scope.row)">
                {{ item }}
              </el-tag>
              <!--             添加标签-->
              <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisable"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                  style="width:150px"
              >
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
            </template>
          </el-table-column>
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column label="属性名称" prop="attr_name"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)"></el-button>
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParams(scope.row.attr_id)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </el-card>
<!--  添加参数的dialog-->
  <el-dialog
      :title="'添加'+titleText"
      :visible.sync="addDialog"
      width="50%"
      @close="addForm.attr_name=''">
    <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
      <el-form-item :label="titleText" prop="attr_name">
        <el-input v-model="addForm.attr_name"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
    <el-button @click="addDialog = false">取 消</el-button>
    <el-button type="primary" @click="addParams">确 定</el-button>
  </span>
  </el-dialog>
  <!--  修改参数的dialog-->
  <el-dialog
      :title="'修改'+titleText"
      :visible.sync="editDialog"
      width="50%"
      @close="editForm.attr_name=''">
    <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
      <el-form-item :label="titleText" prop="attr_name">
        <el-input v-model="editForm.attr_name"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
    <el-button @click="editDialog = false">取 消</el-button>
    <el-button type="primary" @click="editParams">确 定</el-button>
  </span>
  </el-dialog>
</div>
</template>

<script>
import bread from "@/components/bread";
export default {
  name: "params",
  components:{ bread },
  data(){
    return{
      breadList:[],
      cateList:[],
      selectedKey:'',
      activeName:'many',
      manyTableData:[],
      onlyTableData:[],
      inputValue:'',
      addDialog:false,
      editDialog:false,
      inputVisible:false,
      addForm:{
        attr_name:''
      },
      editForm:{
        attr_name:''
      },
      addFormRules:{
        attr_name: [{
          required:true ,message:'请输入参数名称', trigger:'blur'
        }]
      },
      editFormRules:{
        attr_name: [{
          required:true ,message:'请输入参数名称', trigger:'blur'
        }]
      }
    }
  },
  async created() {
    const { data: res } = await this.$http.get('menus')
    this.breadList.push(res.data[2].authName)
    this.breadList.push(res.data[2].children[1].authName)
    this.$refs.bread.getBreadList(this.breadList)
    await this.getCateList()
  },
  methods:{
    //获取数据
    async getCateList() {
      const {data:res} =  await this.$http.get('categories/')
      if(res.meta.status===200){
        this.cateList=res.data
      }else {
        this.$message.error(res.meta.msg)
      }
    },
    //点击级联选择框
    async parentCateChange(){
      console.log(this.selectedKey)
      await this.getParamsData()
    },
    //tab页切换
    handleTabClick(){
      this.getParamsData()
    },
    //获取参数列表
    async getParamsData(){
      const id=this.selectedKey[this.selectedKey.length-1]
      const { data:res} =await this.$http.get('categories/'+id+'/attributes',{params:{ sel:this.activeName}})
      res.data.forEach(item=>{
        item.attr_vals=item.attr_vals ? item.attr_vals.split(' '):[]
        item.inputVisable=false
        item.inputValue=''
      })
      console.log(res)
      if(res.meta.status===200){
        this.$message.success(res.meta.msg)
      }
      else{
        this.$message.error(res.meta.msg)
      }
      if (this.activeName ==='many'){
        this.manyTableData=res.data
      }
      else {
        this.onlyTableData=res.data
      }
    },
    //添加参数
    addParams(){
      this.$refs.addFormRef.validate(async valid=>{
        if (!valid)return
        var id=this.selectedKey[this.selectedKey.length-1]
       const { data:res} =await this.$http.post('categories/'+id+'/attributes',
           {attr_name:this.addForm.attr_name, attr_sel:this.activeName})
        console.log(res)
        this.addDialog=false
      })
    },
    //展示修改弹窗
    async showEditDialog(attrId){
      this.editDialog=true
      var id=this.selectedKey[this.selectedKey.length-1]
      const { data:res} =await this.$http.get('categories/'+id+'/attributes/'+attrId,{params:{attr_sel:this.activeName}})
      this.editForm.attr_name=res.data.attr_name
      this.editForm.attr_id=res.data.attr_id
    },
    //修改参数
    editParams(){
      this.$refs.editFormRef.validate(async valid=>{
        var id=this.selectedKey[this.selectedKey.length-1]
        const { data:res} =await this.$http.put("categories/"+id+"/attributes/"+this.editForm.attr_id,{attr_sel:this.activeName,attr_name:this.editForm.attr_name})
        if(res.meta.status===200){
          this.$message.success(res.meta.msg)
        }
        else{
          this.$message.error(res.meta.msg)
        }
        this.editDialog=false
        await this.getParamsData()
      })
    },
    //删除参数
    async deleteParams(attrId){
      this.$confirm('此操作将永久删除该属性, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then( async () => {
        var id=this.selectedKey[this.selectedKey.length-1]
        const { data:res} =await this.$http.delete("categories/"+id+"/attributes/"+attrId)
        if (res.meta.status ===200){
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
         await this.getParamsData()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //添加标签
    async handleInputConfirm(row){
      var id=this.selectedKey[this.selectedKey.length-1]
      if(row.inputValue.trim().length===0){
         row.inputVisable=''
         row.inputVisable=false
        return
      }
      row.attr_vals.push(row.inputValue.trim()
      )
      row.inputValue=''
      row.inputVisable=false
      const {data:res} = await this.$http.put('categories/'+id+'/attributes/'+row.attr_id,{
        attr_name:row.attr_name,
        attr_sel:row.attr_sel,
        attr_vals:row.attr_vals.join((' '))
      })
      console.log(res)
    },
    showInput(row){
     row.inputVisable=true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //删除标签
    async deleteTag(index,row){
      row.attr_vals.splice(index,1)
      var id=this.selectedKey[this.selectedKey.length-1]
      const {data:res} = await this.$http.put('categories/'+id+'/attributes/'+row.attr_id,{
        attr_name:row.attr_name,
        attr_sel:row.attr_sel,
        attr_vals:row.attr_vals.join((' '))
      })
    }
  },
  computed:{
    Button(){
      return this.selectedKey.length !== 3;
    },
    titleText(){
      if (this.activeName==='many'){
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style scoped>

</style>

